<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link rel="stylesheet" href="index.css">
	</head>
	<body>
		<div class="box" id="box">
		    <div id="smallBox" class="small ">
		        <img src="http://www.jq22.com/demo/jQueryMagnifier201702271056/images/2.png" width="350">
		        <div id="mask" class="mask"></div>
		    </div>
		    <div id="bigBox" class="big">
		        <img src="http://www.jq22.com/demo/jQueryMagnifier201702271056/images/2.png" alt="" id="bigPic">
		    </div>
		</div>
		<script type="text/javascript">
			var smallBox = document.getElementById('smallBox');
			var mask = document.getElementById('mask');
			var bigBox = document.getElementById('bigBox');
			var box = document.getElementById('box')
			var bigPic = document.getElementById('bigPic')
	
			//鼠标经过小盒子，显示大盒子
			smallBox.onmouseenter=function(e){
				mask.style.display='block'
				bigBox.style.display='block'
			}
			//鼠标移出小盒子，不显示大盒子
			smallBox.onmouseleave=function(e){
				mask.style.display='none'
				bigBox.style.display='none'
			}
			smallBox.onmousemove=function(e){
				//遮罩跟随鼠标
				var event = e || window.event
				var pageX = event.pageX || event.clientX + document.documentElement.scrollLeft;
				var pageY = event.pageY || event.clientY + document.documentElement.scrollTop;
				// console.log('pageX==>', pageX)
				// console.log('pageY==>', pageY)
				//计算mask的位置
				var targetX = pageX - box.offsetLeft - mask.offsetWidth / 2;
				var targetY = pageY - box.offsetTop - mask.offsetHeight / 2;
				//限制mask移动范围
				if (targetX < 0) {
					targetX = 0;
				}
				if (targetY < 0) {
					targetY = 0;
				}
				if(targetX > smallBox.offsetWidth - mask.offsetWidth) {
					targetX = smallBox.offsetWidth - mask.offsetWidth
				}
				if(targetY > smallBox.offsetHeight - mask.offsetHeight) {
					targetY = smallBox.offsetHeight - mask.offsetHeight
				}
				// 移动mask
				mask.style.left = targetX + "px";
    			mask.style.top = targetY + "px";
				// 
				var bigXInstance = bigPic.offsetWidth - bigBox.offsetWidth
				var smallXInstance = smallBox.offsetWidth - mask.offsetWidth
				var Xrate = bigXInstance / smallXInstance

				var bigYInstance = bigPic.offsetHeight - bigBox.offsetHeight
				var smallYInstance = smallBox.offsetHeight - mask.offsetHeight
				var Yrate = bigYInstance / smallYInstance

				bigPic.style.left = Xrate * -targetX + 'px'
				bigPic.style.top = Xrate * -targetY +'px'
			}
		</script>
	</body>
</html>
